package org.bonorsoft.common.system.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.system.vo.LoginDingUser;
import org.bonorsoft.common.system.vo.LoginUser;
import org.bonorsoft.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: Controller基类
 * @Author: dangzhenghui@163.com
 * @Date: 2019-4-21 8:13
 * @Version: 1.0
 */
@Slf4j
public class BonorController<T, S extends IService<T>> {
    @Autowired
    S service;

    @Value(value = "${william.path.upload}")
    private String uploadpath;

    /**
     * 导出excel
     *
     * @param request
     */
    protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title) {
        // Step.1 组装查询条件
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
        LoginDingUser sysUser = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<T> exportList = getExportList(request, queryWrapper);

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        //三句代替下面注释一句 解决图像路径问题
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getName(), title);
        exportParams.setImageBasePath(uploadpath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        //mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getName(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 根据模板导出excel
     * @param params
     * @param map
     * @param request
     * @param object
     * @param clazz
     * @param title
     * @return
     */
    protected ModelAndView exportXlsByTemplate(TemplateExportParams params, Map<String, Object> map, HttpServletRequest request, T object, Class<T> clazz, String title) {
        // Step.1 组装查询条件
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());

        // Step.2 获取导出数据
        List<T> exportList = getExportList(request, queryWrapper);

        return getModelAndView(params, map, clazz, title, exportList);

    }

    /**
     * 获取对象ID
     *
     * @return
     */
    private String getId(T item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            //设置为true，导入完成后总会重启系统
            //params.setNeedSave(true);
            try {
                List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                service.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 下载模板信息
     * @param clazz
     * @param title
     * @return
     */
    protected ModelAndView importTemplateXls(Class<T> clazz, String title) {
        // Step.1 组装查询条件
        LoginDingUser sysUser = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<T> exportList = new ArrayList<>();

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "填报人:" + sysUser.getName(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 下载自定义模板
     * @param params
     * @param map
     * @param clazz
     * @param title
     * @return
     */
    protected ModelAndView importTemplateByExcel(TemplateExportParams params, Map<String, Object> map, Class<T> clazz, String title) {
        List<T> exportList = new ArrayList<>();
        return getModelAndView(params, map, clazz, title, exportList);
    }


    /**
     * 获取当前登陆者姓名
     * @return name
     */
    protected String getLoginUserName(){
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();
        return user.getName();
    }

    /**
     * 获取当前登陆者姓名
     * @return userid
     */
    protected String getLoginUserId(){
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();
        return user.getUserid();
    }

    /**
     * 生成模板excel
     * @param params
     * @param map
     * @param clazz
     * @param title
     * @param exportList
     * @return
     */
    private ModelAndView getModelAndView(TemplateExportParams params, Map<String, Object> map, Class<T> clazz, String title, List<T> exportList) {
        map.put("people", getLoginUserName());
        ModelAndView mv = new ModelAndView(new JeecgTemplateExcelView());
        mv.addObject(TemplateExcelConstants.FILE_NAME, title);
        mv.addObject(TemplateExcelConstants.LIST_DATA, exportList);
        mv.addObject(TemplateExcelConstants.MAP_DATA, map);
        mv.addObject(TemplateExcelConstants.CLASS, clazz);
        mv.addObject(TemplateExcelConstants.PARAMS, params);
        return mv;
    }

    /**
     * 获取导出数据
     * @param request
     * @param queryWrapper
     * @return
     */
    private List<T> getExportList(HttpServletRequest request, QueryWrapper<T> queryWrapper) {
        List<T> pageList = service.list(queryWrapper);
        List<T> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }
        return exportList;
    }
}
